//
//  CXYSocket.swift
//  诚叙缘
//
//  Created by sujeking on 17/4/18.
//  Copyright © 2017年 szw. All rights reserved.
//

import UIKit

import SocketRocket
import YYModel


class ChatUserModel: NSObject {
    open var from_uid:String?
    open var to_uid:String?
    open var send_msg:String?
}


@objc protocol CXYSocketDelegate: NSObjectProtocol {
    @objc optional func getOnlineList(list:Array<Any>)-> Void
    @objc optional func receiveMsg(msg:String)-> Void
    @objc optional func loginStatus(status:Bool) -> Void
}





class CXYSocket: NSObject {
    var webSocket:SRWebSocket!
    var model:ChatUserModel!
    open var delegate: CXYSocketDelegate?
    
    var conn_status:Bool! = false
    open var receive:String?
}

extension CXYSocket {
    open func login(userName:String!) {
        self.connetServer()
        self.model = ChatUserModel()
        self.model.from_uid = userName
    }
    
    open func send_msg_to(msg:String?,uid:String!) {
        self.model.send_msg = msg
        self.model.to_uid = uid
        self.sendMsg(isLogin: false)
    }
    
    open func loginout(){
        self.webSocket.delegate = nil;
        self.webSocket.close();
        self.delegate?.loginStatus!(status: false)
    }
    
    open func connetServer() {
        self.webSocket = SRWebSocket(url: URL(string:"ws://192.168.33.65:8080"))
        self.webSocket.delegate = self
        self.webSocket.open()
    }
    
    func sendMsg(isLogin:Bool) {
        var msg:String!
        if isLogin {
            msg = "{\"cmd\":\"login\",\"uid\":\"" + self.model.from_uid! + "\"}"
        } else {
            msg = "{\"cmd\":\"msg\",\"from\":\"" + self.model.from_uid! + "\",\"to\":\"" + self.model.to_uid! + "\",\"msg\":\"" + self.model.send_msg! + "\"}"
        }
        self.webSocket.send(msg)
    }
    
    func getOnlineMember() {
        let msg = "{\"cmd\":\"getList\"}"
        if self.conn_status == true {
            self.webSocket.send(msg);
        }
    }
    
}

extension CXYSocket:SRWebSocketDelegate {
    
    func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
        let s_msg = message as! String
        let data: Data = s_msg.data(using: String.Encoding.utf8)!
        do{
            let result = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
            let key = result["cmd"] as! String
            
            if key == "login" {
                self.delegate?.loginStatus!(status: true)
            } else if key == "getList" {
                self.delegate?.getOnlineList!(list: result["list"] as! Array<Any>)
            } else if key == "msg" {
                self.delegate?.receiveMsg!(msg: (result["msg"] as? String)!)
            }
        } catch let error {
            print(error)
        }
    }
    
    func webSocketDidOpen(_ webSocket: SRWebSocket!) {
        self.conn_status = true
        self.sendMsg(isLogin: true)
    }
    
    public func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!) {
        self.conn_status = false
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
        // close
        self.webSocket.delegate = nil
        self.webSocket.close()
    }
    
    //    public func webSocket(_ webSocket: SRWebSocket!, didReceivePong pongPayload: Data!) {
    //
    //    }
    //
    //    public func webSocketShouldConvertTextFrame(toString webSocket: SRWebSocket!) -> Bool {
    //        return true
    //    }
    
}
